<!-- 空气 -->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="">
          <el-date-picker v-model="params.date" type="month" format="yyyy年MM月" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接入单位">
          <el-select v-model="params.userInfoId" placeholder="请选择接入单位" clearable="" @change="selectTrigger">
            <el-option v-for="(item,index) in companyList" :key="index" :label="item.deviceName"
              :value="item.deviceMac">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="handleFilter" :loading="btnLoading">查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row v-if="params.userInfoId !== '-1'">
      <el-button v-for="(item,index) in deviceList" :key="index+'-device'" :type="item.type"
        @click="deviceOnclick(item)">{{'[' +item.deviceMac +' ] ' + item.deviceName}}</el-button>
    </el-row>

    <div class="content-2" v-show="params.userInfoId !== '-1'">
      <!-- 显示折线图 -->
      <!-- <div style="margin-top:20px">告警次数曲线</div> -->
      <div id="ywbjCharts"      :style="{width:'1000px',height:'240px'}" style="font-size:small;margin-top: 30px;"></div>
      <div id="yysjycCharts"    :style="{width:'1000px',height:'240px'}"></div>
      <div id="ycCharts"    :style="{width:'1000px',height:'240px'}"></div>
      <div id="ldbyycCharts"    :style="{width:'1000px',height:'240px'}"></div>
      <div id="scdyycCharts"    :style="{width:'1000px',height:'240px'}"></div>
      <div id="scdlycCharts"    :style="{width:'1000px',height:'240px'}"></div>
      <div id="fjwzjsjycCharts" :style="{width:'1000px',height:'240px'}"></div>
      <div id="klwycCharts"     :style="{width:'1000px',height:'240px'}"></div>

    </div>
    <div class="content" v-show="params.userInfoId === '-1'">
      <div class="charts-left">
        <!-- 饼状图 -->
        <div id="myCharts" :style="{width:'100%',height:'200px'}"></div>
        <div style="margin-top: 40px;">
          <el-table :header-cell-style="{background:'#EFEFEF',color:'#606266'}" :data="mLabelList" style="width: 100%">
            <el-table-column prop="name" label="告警事件类型" min-width="50%">
            </el-table-column>
            <el-table-column prop="value" label="次数" min-width="25%">
            </el-table-column>
            <el-table-column prop="zb" label="占比" min-width="25%">
            </el-table-column>
          </el-table>
        </div>


      </div>
      <div class="charts-right">
        <!-- 水平柱状图 -->
        <div id="zztCharts" :style="{width:'100%',height:'650px'}"></div>
      </div>

    </div>
  </div>
</template>

<script>
  import { getPoliceNumByType, queryPoliceTypeNum } from '@/api/warn'
  import { queryUserInfoAll, queryDeviceByUserInfoIdPage } from '@/api/isp'
  import { mapGetters } from 'vuex'
  import echarts from 'echarts'

  export default {
    name: 'Warn',
    computed: {
      ...mapGetters([
        'token'
      ])
    },
    components: {
    },
    data() {
      return {
        btnLoading: false,
        deviceList: [],
        companyList: [], //服务商列表
        params: {
          date: '',
          userInfoId: '-1' //服务商ID
        },
        userId: '',
        chart: null,
        zztChart: null,
        mParams: {
          type: 2,
          startTime: '',
          endTime: ''
        },
        mTBParams: {
          'deviceMac': '',		// 设备mac
          'type': 2,	// 值为1为每小时  2为每天 3每月
          'startTime': '',	// 开始时间
          'endTime': ''		// 结束时间
        },
        mLabelList: [], //标签list
        mTotalData: 0, //告警总数
        optionBT: {//饼图
          title: {
            text: '告警事件次数占比',
            subtext: '',
            top: 'top'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          series: [
            {
              // name: '访问来源',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: [],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }, //饼图
        optionZT: {//水平柱状图
          title: {
            text: '月度告警次数TOP20',
            subtext: ''
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },

          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          series: [
            {
              name: '告警次数',
              type: 'bar',
              data: []
            }
          ]
        },
        ywbjChart: null, //有位报警
        ywbjOption: {
          title: {
            text: '有报警位分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        yysjycChart: null, //油烟数据异常
        yysjycOption: {
          title: {
            text: '油烟数据异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        ldbycChart: null, //联动比异常
        ldbycOption: {
          title: {
            text: '联动比异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        scdyycChart: null, //输出电压异常
        scdyycOption: {
          title: {
            text: '输出电压异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        scdlycChart: null, //输出电流异常
        scdlycOption: {
          title: {
            text: '输出电流异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        fjwzjsjycChart: null, //非甲烷总烃（ting）数据异常
        fjwzjsjycOption: {
          title: {
            text: '非甲烷总烃数据异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
        klwycChart: null, //颗粒物异常
        klwycOption: {
          title: {
            text: '颗粒物异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        },
  
        ycChart: null, //压差
        ycOption: {
          title: {
            text: '压差异常分析',
            'textStyle': {
              'fontSize': 14
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              magicType: { type: ['line', 'bar'] },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '告警次数',
              type: 'line',
              data: [],
              markPoint: {
                data: [
                  { type: 'max', name: '最大值' }
                ]
              }
            }
          ]
        }

      }
    },
    watch: {
      // 搜索条件体
      params: {
        handler: function(val, oldVal) {

        },
        deep: true
      }
    },
    mounted() {
      this.initECharts()
    },
    created() {
      this.userId = this.token
      var date1 = new Date()
      console.log('date :>> ', date1)
      // var currentMonth = date1.getMonth() + 1 > 9 ? date1.getMonth() + 1 : '0' + (date1.getMonth() + 1)
      // this.params.date = date1.getFullYear() + '年' + currentMonth + '月'
      var currentdate = this.getDate(1, true, '', '')
      this.params.date = currentdate
      this.mParams.startTime = currentdate
      var endDate = this.getDate(2, true, '', '')
      this.mParams.endTime = endDate
      // 取列表
      this.getCompanyList()
      //获取所有告警列表
      this.getTotalWarn()
    },
    activated() {
      // 取列表
      this.getCompanyList()
    },
    methods: {
      initECharts() {
        this.chart = echarts.init(document.getElementById('myCharts'))
        this.zztChart = echarts.init(document.getElementById('zztCharts'))
        this.ywbjChart = echarts.init(document.getElementById('ywbjCharts'))
        this.yysjycChart = echarts.init(document.getElementById('yysjycCharts'))
        this.ycChart = echarts.init(document.getElementById('ycCharts'))
        this.ldbycChart = echarts.init(document.getElementById('ldbyycCharts'))
        this.scdyycChart = echarts.init(document.getElementById('scdyycCharts'))
        this.scdlycChart = echarts.init(document.getElementById('scdlycCharts'))
        this.fjwzjsjycChart = echarts.init(document.getElementById('fjwzjsjycCharts'))
        this.klwycChart = echarts.init(document.getElementById('klwycCharts'))
      },
      selectTrigger(e) {
        console.log('e :>> ', e)
        if (e !== '-1') {
          this.queryDevice(e * 1)
        } else {
          // this.initECharts()
          console.log('this.params.date :>> ', this.params.date)
          this.mParams.startTime = this.params.date
          var time = this.params.date
          var split = time.split('-')
          var result = this.getDate(2, false, split[0], split[1])
          this.mParams.endTime = result
          this.getTotalWarn()
        }
      },
      handleFilter(val) {
        if (this.params.userInfoId === '') {
          this.params.userInfoId = '-1'
        }
        console.log('this.params.userInfoId :>> ', this.params.userInfoId)
        if (this.params.userInfoId !== '-1') {
          this.queryDevice(this.params.userInfoId)
        } else {
          console.log('this.params.date :>> ', this.params.date)
          this.mParams.startTime = this.params.date
          var time = this.params.date
          var split = time.split('-')
          var result = this.getDate(2, false, split[0], split[1])
          this.mParams.endTime = result
          this.getTotalWarn()
        }
      },
      deviceOnclick(e) {
        for (let i = 0; i < this.deviceList.length; i++) {
          const mInfo = this.deviceList[i]
          if (mInfo.deviceMac === e.deviceMac) {
            mInfo.type = 'primary'
            if (mInfo.deviceMac !== this.mTBParams.deviceMac) {
              this.mTBParams.deviceMac = mInfo.deviceMac
              this.mTBParams.startTime = this.params.date
              var time = this.params.date
              var split = time.split('-')
              var result = this.getDate(2, false, split[0], split[1])
              this.mTBParams.endTime = result
              this.searchData()
            }
          } else {
            mInfo.type = 'deafult'
          }
        }
      },
      queryDevice(val) {
        queryDeviceByUserInfoIdPage(this.params.userInfoId * 1).then(res => {
          console.log('res :>> ', res)
          var mList = []
          for (let i = 0; i < res.data.length; i++) {
            const element = res.data[i]
            var mItem = { deviceMac: element.deviceMac, deviceName: element.deviceName, type: i === 0 ? 'primary' : 'deafult' }
            mList.push(mItem)
          }
          this.deviceList = mList
          if (this.deviceList.length > 0) {
            var item = this.deviceList[0]
            this.mTBParams.deviceMac = item.deviceMac
            this.mTBParams.startTime = this.params.date
            var time = this.params.date
            var split = time.split('-')
            var result = this.getDate(2, false, split[0], split[1])
            this.mTBParams.endTime = result
            this.searchData()
          }
        }).catch(err => {
          err
        })
      },
      getCompanyList() {
        var mList = []
        queryUserInfoAll(this.userId).then(res => {
          mList.push({ deviceMac: '-1', deviceName: '全部' })
          for (let i = 0; i < res.data.length; i++) {
            const element = res.data[i]
            mList.push(element)
          }
          this.companyList = mList
        }).catch(err => { err })
      },
      getTotalWarn() {
        this.params.type = 1
        console.log('this.params :>> ', this.mParams)
        getPoliceNumByType({ userId: this.userId * 1, type: 1, startTime: this.mParams.startTime, endTime: this.mParams.endTime }).then(res => {
          const result = res.data
          // this.optionBT.legend.data = []
          // this.optionBT.series[0].data = []
          var mList = []
          var mContentList = []
          for (let i = 0; i < result.length; i++) {
            const element = result[i]
            if (element.timeHour !== 'totalData') {
              var last = result[result.length - 1].policeNum
              var zb = ((element.policeNum / last) * 100).toFixed(2) + '%'
              var lab = { value: element.policeNum, name: element.timeHour, zb: zb }
              mList.push(lab)
              var po = { value: element.policeNum, name: element.timeHour }
              mContentList.push(po)
            } else {
              this.mTotalData = element.policeNum
            }
          }
          // this.optionBT.legend.data = mList
          this.mLabelList = mList
          this.optionBT.series[0].data = mContentList
          this.chart.setOption(this.optionBT)
          console.log('type1  类型列表 :>> ', res)
        }).catch(err => {
          err
        })
        var mDevList = []
        var mValueList = []
        getPoliceNumByType({ userId: this.userId * 1, type: 2, startTime: this.mParams.startTime, endTime: this.mParams.endTime }).then(res => {
          console.log('type2 设备排行列表 :>> ', res)
          var devResult = res.data
          for (let j = 0; j < devResult.length; j++) {
            const element = devResult[j]
            if (element.timeHour !== 'totalData') {
              mDevList.push(element.timeHour)
              mValueList.push(element.policeNum)
            }
          }
          this.optionZT.yAxis.data = mDevList
          this.optionZT.series[0].data = mValueList
          this.zztChart.setOption(this.optionZT)
        }).catch(err => {
          err
        })
      },

      //  获取本月的第一天和最后一天， type1第一天，type2最后一天
      //  isCurrentMonth // true 当前月
      getDate(type, isCurrentMonth, year, month) {
        var nowMonth, nowYear
        if (isCurrentMonth) {
          var now = new Date() //当前日期
          nowMonth = now.getMonth() //当前月
          nowYear = now.getFullYear() //当前年
        } else {
          nowYear = year
          nowMonth = month * 1 - 1
        }

        //本月的开始时间
        //本月的结束时间
        if (type === 1) {
          var monthStartDate = new Date(nowYear, nowMonth, 1)
          // var timeStar = Date.parse(monthStartDate) / 1000//s
          // return timeStar
          var month1 = monthStartDate.getMonth() + 1 > 9 ? (monthStartDate.getMonth() + 1) : '0' + (monthStartDate.getMonth() + 1)
          debugger
          return monthStartDate.getFullYear() + '-' + month1 + '-01 00:00:00'
        } else {
          var monthEndDate = new Date(nowYear, nowMonth + 1, 0)
          var month2 = monthEndDate.getMonth() + 1 > 9 ? (monthEndDate.getMonth() + 1) : '0' + (monthEndDate.getMonth() + 1)
          return monthEndDate.getFullYear() + '-' + month2 + '-' + monthEndDate.getDate() + ' 00:00:00'
          // var timeEnd = Date.parse(monthEndDate) / 1000//s
          // return timeEnd
        }
      },
      searchData() {
        var dayList = []
        var days = this.getCountDays()
        for (let i = 1; i <= days; i++) {
          // const day = days[i]
          dayList.push(i)
        }
        this.ywbjOption.xAxis.data = dayList
        this.yysjycOption.xAxis.data = dayList
        this.ycOption.xAxis.data = dayList
        this.ldbycOption.xAxis.data = dayList
        this.scdyycOption.xAxis.data = dayList
        this.scdlycOption.xAxis.data = dayList
        this.fjwzjsjycOption.xAxis.data = dayList
        this.klwycOption.xAxis.data = dayList
        var _that = this
        queryPoliceTypeNum(this.mTBParams).then(res => {
          console.log('查询折线图 :>> ', res)
          var result = res.data
          var ywbjList = result.ybjw
          var list1 = []
          var newList1 = _that.bubbleSort(ywbjList)
          console.log('newList1 :>> ', newList1)
          for (let a = 0; a < newList1.length; a++) {
            const e1 = newList1[a]
            list1.push(e1.policeNum)
          }
          _that.ywbjOption.series[0].data = list1
          _that.ywbjChart.setOption(_that.ywbjOption)
          var yysjycList = result.yysj
          var list2 = []
          var newList2 = _that.bubbleSort(yysjycList)
          for (let b = 0; b < newList2.length; b++) {
            const e2 = newList2[b]
            list2.push(e2.policeNum)
          }
          _that.yysjycOption.series[0].data = list2
          _that.yysjycChart.setOption(_that.yysjycOption)

          var ldbycList = result.ldb
          var list3 = []
          var newList3 = _that.bubbleSort(ldbycList)
          for (let c = 0; c < newList3.length; c++) {
            const e3 = newList3[c]
            list3.push(e3.policeNum)
          }
          _that.ldbycOption.series[0].data = list3
          _that.ldbycChart.setOption(_that.ldbycOption)

          var scdyycList = result.scdl
          var list4 = []
          var newList4 = _that.bubbleSort(scdyycList)
          for (let d = 0; d < newList4.length; d++) {
            const e4 = newList4[d]
            list4.push(e4.policeNum)
          }

          _that.scdyycOption.series[0].data = list4
          _that.scdyycChart.setOption(_that.scdyycOption)
          var scdlycList = result.scdy
          var list5 = []
          var newList5 = _that.bubbleSort(scdlycList)
          for (let e = 0; e < newList5.length; e++) {
            const e5 = newList5[e]
            list5.push(e5.policeNum)
          }
          _that.scdlycOption.series[0].data = list5
          _that.scdlycChart.setOption(_that.scdlycOption)

          var fjwzjsjycList = result.fjwzj
          var list6 = []
          var newList6 = _that.bubbleSort(fjwzjsjycList)
          for (let f = 0; f < newList6.length; f++) {
            const e6 = newList6[f]
            list6.push(e6.policeNum)
          }
          _that.fjwzjsjycOption.series[0].data = list6
          _that.fjwzjsjycChart.setOption(_that.fjwzjsjycOption)
          var klwycList = result.klw
          var list7 = []
          var newList7 = _that.bubbleSort(klwycList)
          for (let g = 0; g < newList7.length; g++) {
            const e7 = newList7[g]
            list7.push(e7.policeNum)
          }
          _that.klwycOption.series[0].data = list7
          _that.klwycChart.setOption(_that.klwycOption)

          var ycList = result.yc
          var list8 = []
          var newList8 = _that.bubbleSort(ycList)
          for (let h = 0; h < newList8.length; h++) {
            const e8 = newList8[h]
            list8.push(e8.policeNum)
          }
          _that.ycOption.series[0].data = list8
          _that.ycChart.setOption(_that.ycOption)
        }).catch(err => { err })
      },
      /*获取一个月的天数 */
      getCountDays() {
        var time = this.params.date
        var split = time.split('-')
        var curDate = new Date(split[0], split[1], 0)
        return curDate.getDate()
      },
      //从小到大排序
      bubbleSort(mList) {
        if (Array.isArray(mList)) {
          var arr = mList
          var min
          for (var i = 0; i < arr.length; i++) {
            for (var j = i; j < arr.length; j++) {
              if ((arr[i].timeHour * 1) > (arr[j].timeHour * 1)) {
                min = arr[j]
                arr[j] = arr[i]
                arr[j] = min
              }
            }
          }
          return arr
        }
      }
    }

  }

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .content-2 {
    width: 100%;
    flex-direction: column;
    justify-content: center;
  }
  .charts-left {
    width: 50%;
    padding: 20px;
    align-items: center;
  }

  .charts-right {
    width: 50%;
    padding: 20px;
  }
</style>